package com.javen.bankpay;

import java.util.List;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Record;


public class AgentController extends Controller {
	static Log log = Log.getLog(AgentController.class);
	static AgentService agentService = new AgentService();

	public Record parseReqToRecord(){
		Record r = new Record();
		Map<String, String[]> map = getParaMap();
		Set<String> set = map.keySet();
		Iterator<String> it = set.iterator();
		while(it.hasNext()){
			String key = it.next();
			if(!key.equals("time")&!key.equals("signature")&&!key.equals("salt")){
				String[] s = map.get(key);
				r.set(key, s[0]);
			}
		}
		return r;
	}
	
	/*
	 * 绑定商户号
	 */
	public void bind(){
		Record r = parseReqToRecord();
		List<Record> agent_trans = agentService.findAgentTrans(r.getStr("mch_id"), r.getStr("mch_name"));
		if(agent_trans.size() > 0){
			List<Record> agents = agentService.findAgents(r.getStr("openID"), r.getStr("mch_id"));
			if(agents.size() > 0){
				renderText("same");
			}else{
				agentService.save(r);
				renderText("success");
			}
		}else{
			renderText("商户号与商户名不符！");
		}
	}
	
	/*
	 * 查询用户绑定的所有商户号
	 */
	public void getMchs(){
		String openID = getPara("openID");
		List<Record> agents = agentService.findAgents(openID, "");
		renderJson(new Record().set("list", agents));
	}
	
	/*
	 * 查询商户交易记录
	 */
	public void getOrders(){
		String number = getPara("number");
		String dateFrom = getPara("dateFrom");
		String dateTo = getPara("dateTo");
		String type = getPara("type");
		int page = getParaToInt("page");
		int start = (page - 1) * 5;
		int count = agentService.getOrderCount(number, dateFrom, dateTo, type);
		count = (count / 5) + 1;
		List<Record> list = agentService.getOrders(number, dateFrom, dateTo, type, start);
		renderJson(new Record().set("count", count).set("list", list));
	}
	
	

}
